<template>
  <div class="app-container">
    <div class="filter-container">

      <router-link :to="{path:'/admin/chapter_add', query:{courseid:listQuery.CourseId}}">
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit">
           增加
         </el-button>
      </router-link>

      <el-input v-model="listQuery.name" placeholder="请输入名称" style="width:250px;" class="filter-item" @keyup.enter.native="handleFilter" />
    <!--  <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select> -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>

      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    <!--  <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      row-key="id"
      :tree-props="{children: 'childs'}"
    >
      <el-table-column label="行号" type="index"  align="center" width="50">
      </el-table-column>
     <!-- <el-table-column label="课程ID" prop="id" width="50" sortable="custom" :class-name="getSortClass('id')">
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="标题" min-width="120" header-align	="center" >
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="封面" width="90"   align="center">
        <template slot-scope="{row}">
          <span>
            <el-image :src="$baseUrl+row.pic" lazy class="img50" fit="cover">
              <div slot="placeholder" class="image-slot">
                      <i class="el-icon-loading" />
              </div>
              <div slot="error" class="image-slot"><i class="el-icon-picture-outline"></i></div>
            </el-image>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="简介" min-width="180"  align="center">
        <template slot-scope="{row}">
          <span>{{ row.intro }}</span>
        </template>
      </el-table-column>
      <el-table-column label="附件" width="90"  align="center">
        <template slot-scope="{row}">
          <span></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <router-link :to="{path:'/admin/chapter_add?'+Param({parentId:row.id,parentName:row.name,courseid:listQuery.CourseId})}">
            <el-button type="success" size="mini">
              子章节
            </el-button>
          </router-link>
          <router-link :to="{path:'/admin/chapter_add', query: {id:row.id}}">
            <el-button type="primary" size="mini">
             修改
            </el-button>
          </router-link>
         <!-- <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">
            Publish
          </el-button>
          <el-button v-if="row.status!='draft'" size="mini" @click="handleModifyStatus(row,'draft')">
            Draft
          </el-button> -->
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="getList" />
  </div>
</template>

<script>
import API from '@/api/chapter'
import waves from '@/directive/waves' // waves directive
import { parseTime, param } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination


export default {
  name: 'chapter',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {

    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        CourseId:null,
        sort: '+id'
      },
      importanceOptions: [],

      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改 ',
        create: '增加'
      },
      dialogPvVisible: false,
      pvData: [],
      downloadLoading: false
    }
  },
  created() {
    this.listQuery.CourseId=this.$route.query.courseid
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      API.fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 10)
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    handleDelete(row, index) {
      this.$confirm('确认删除吗?', '提醒', {confirmButtonText:'确定',cancelButtonText: '取消',type: 'warning'}).then(() => { //点击确定的操作(调用接口)
         API.delete(row.id).then(() => {
           this.$notify({
             title: '提示',
             message: '删除成功！',
             type: 'success',
             duration: 2000
           })
          //if(row.parentId){
               this.getList()  //树形结构暂时这样刷新
           //}else{
            // this.list.splice(index, 1)
           //}
         })

      }).catch(() => { })//几点取消的提醒

    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id', 'name', 'intro']
        const filterVal = ['id', 'name', 'intro']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'chapter-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    Param(json){
      return param(json)
    }
  }
}
</script>
